package Bai08;

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JPanel;


@SuppressWarnings("serial")
public class RemoteCanvas extends JFrame{
	JPanel canvas = new JPanel();
	DatagramSocket socket;
	DatagramPacket dp;
	InetAddress ia;
	Graphics2D g2d;
	public RemoteCanvas(String title) {
		super(title);
		setSize(400,300);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		setContentPane(canvas);
		socketInit(2048);
		run();
	}
	public void socketInit(int port){
		try {
			socket = new DatagramSocket(port);
			ia = InetAddress.getLocalHost();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}		
	}
	public void run(){
		byte[] buffer = new byte[10240];
		dp = new DatagramPacket(buffer, 10240);
		while (true){
			try {
				g2d=(Graphics2D) canvas.getGraphics();
				//g2d.setColor(getBackground());
				//g2d.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
				socket.receive(dp);
				
				Objective obj=ReadObjectFromPacket(dp);
				//System.out.print(obj.getSize());
				g2d.setColor(obj.getColor());
				g2d.setStroke(new BasicStroke(obj.getSize()));
				g2d.drawLine(obj.getStart().x, obj.getStart().y, obj.getEnd().x,obj.getEnd().y);
		
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	

		

		
		
	}
	private Objective ReadObjectFromPacket(DatagramPacket dp)  {
		ByteArrayInputStream bi = new ByteArrayInputStream(dp.getData());
		ObjectInputStream os;
		Objective pic=new Objective();
		try {
			os = new ObjectInputStream(bi);
			pic = (Objective) os.readObject();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return pic;
	}
	
	public static void main(String[] args) {
		new RemoteCanvas("Remote canvas");

	}

}
